package com.olap.starter.common.service.crud.impl.builder;

import com.olap.starter.common.vo.QueryParameter;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExecuteWhereBuilder {

    public void setExecuteWhere(String executeSql, QueryParameter queryParameter) {
        String executeWhere = prepareParams(executeSql, queryParameter.getQueryParameterMap());
        if (executeWhere != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(executeWhere);
            if (queryParameter.getExecuteWhere() != null) {
                sb.append(" AND ").append(queryParameter.getExecuteWhere());
            }
            queryParameter.setExecuteWhere(sb.toString());
        }
    }

    private String prepareParams(String executeSql, Map<String, Object> values) {
        if (executeSql != null) {
            String reg = "#\\{([ ]+|)([a-zA-Z-_'\"]+)([ ]+|)\\}";
            Pattern pattern = Pattern.compile(reg);
            Matcher m = pattern.matcher(executeSql);
            while (m != null && m.find()) {
                String param = m.group(2);
                String value = "";
                if (values != null && values.containsKey(param)) {
                    value = String.valueOf(values.get(param));
                }
                executeSql = executeSql.replace(String.format("#{%s}", param), value);
            }
        }
        return executeSql;
    }
}
